import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCselect {
    public static void main(String[] args) throws SQLException {
        //1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/yjh1?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("yjh20010223");
        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();
        //3.构造sql语句
        String sql = "select * from student1" ;
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        //遍历resultSet结果集
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = "+ id +",name  = " +name);
        }
        //4.释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
